/**
 * @author Aaron
 * @createTime 14:17 2022/5/27
 **/
package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetActivityRecord(uid int) ([]*models_main.UserActivity, error) {
	o := make([]*models_main.UserActivity, 0)
	err := mysql.Condition(mysql.GetRTable(&models_main.UserActivity{}), map[string]interface{}{"uid": uid}, "", "id desc ", 0, 30).
		Find(&o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, nil
}

func GetActivityTypeRecord(uid, typeId int) (*models_main.UserActivity, error) {
	o := &models_main.UserActivity{}
	err := mysql.GetRTable(&models_main.UserActivity{}).
		Where("uid = ? AND  category = ?", uid, typeId).
		First(o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, nil
}

func InsertActivityRecord(tx *gorm.DB, ua *models_main.UserActivity) error {
	err := tx.Create(ua).Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}
